import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import router from 'umi/router';
import styles from './index.less';
import HeaderTab from '@/components/HeaderTab';
import { Card, Switch, Input, Radio, Checkbox, Form, Button, message, Spin, List, Row, Col, Pagination, Popconfirm } from 'antd';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const namespace = 'expresssetting'
@Form.create()
class Express extends React.Component {
  state = {
    Payment: [],
    paginationProps: {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 10,
      total: 0,
      pageIndex: 1,
    },
    tabs: [
      {
        title: '快递发货',
        key: `/${window.storeId}/delivery/express`,
        // disabled: true
      },
      {
        title: '快递单模板',
        key: `/${window.storeId}/delivery/expressbilltemplate/list`,
      },
      {
        title: '物流公司',
        key: `/${window.storeId}/delivery/logistics`,
      },
      // {
      //   title: '物流查询',
      //   key: `/${window.storeId}/delivery/logisticsInquiry`,
      // },
    ],
  }
  // 头部标签页切换
  onTabChange = id => {
    this.setState(
      {
        activeId: id,
      },
      () => {
        router.replace({
          pathname: `${id}`,
        });
        // if(id==1){
        //     router.replace({
        //         pathname: `/${window.storeId}/store/pages`
        //     })
        // }else{
        //     router.replace({
        //         pathname: `/${window.storeId}/store/pages/draft`
        //     })
        // }
      }
    );
  };

  componentWillMount() {
    window.Isoption = false;
    this.getconfig();
    this.GetFreightTemplateWithPage()
  }
  componentDidMount() {
    window.Isoption = true;
  }
  setExpressConfig = (checked) => {
    if (checked) {
      this.openExpress();
    } else {
      this.CloseExpress();
    }
    //this.getconfig();
  }
  onShowSizeChange = (current, pageSize) => {
    console.log('asd')
    let { paginationProps } = this.state;
    let pagination = {
      ...paginationProps,
      pageIndex: current,
      pageSize: pageSize
    };

    this.setState({ paginationProps: pagination }, () => {
      this.GetFreightTemplateWithPage();
    })
  }
  GetFreightTemplateWithPage = () => {
    const { dispatch } = this.props;
    const { paginationProps: { pageIndex, pageSize } } = this.state;
    dispatch({
      type: `${namespace}/GetFreightTemplateWithPage`,
      param: { PageIndex: pageIndex, PageSize: pageSize },
      callback: {
        success: (data) => {

          this.setState({ paginationProps: { ...this.state.paginationProps, total: data.Data.Total } })
        },
        error: (data) => {

        }
      }
    });
  }
  openExpress = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/OpenExpress`,
      callback: {
        success: (data) => {
          message.success("已开启");
          this.getconfig()
        },
        error: (data) => {
          message.error("开启失败：" + data.Msg);
        }
      }
    });
  }

  CloseExpress = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/CloseExpress`,
      callback: {
        success: (data) => {
          message.success("已关闭");
          this.getconfig()
        },
        error: (data) => {
          message.error("关闭失败：" + data.Msg);
        }
      }
    });
  }

  getconfig = () => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/GetExpressConfig`,
      param: { p: Math.random() },
      callback: (data) => {
        let cPayment = []
        if (data.IsSupportCOD) {
          cPayment.push(2)
        }
        if (data.IsSupportOnlinePay) {
          cPayment.push(1)
        }
        this.setState({ Payment: cPayment })
      }
    });
  }
  AddTemplate = () => {
    router.replace({
      pathname: `/${window.storeId}/delivery/express/add`,
    });
  }
  editTemplate = (id) => {
    router.replace({
      pathname: `/${window.storeId}/delivery/express/edit/` + id,
    });
  }
  deleteTemp = (tempId) => {
    const { dispatch } = this.props;
    dispatch({
      type: `${namespace}/DelFreightTemplate`,
      param: { Id: tempId, p: Math.random() },
      callback: {
        success: (data) => {
          message.success('删除成功');
          this.GetFreightTemplateWithPage();
        },
        error: (data) => {
          message.success('删除失败');
        }
      }
    });
  }
  handleSubmit = () => {
    const { dispatch } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let IsSupportOnlinePayIndex = values.Payment.findIndex(item => item == 1)
        if (IsSupportOnlinePayIndex > -1) {
          values = { ...values, IsSupportOnlinePay: true }
        } else {
          values = { ...values, IsSupportOnlinePay: false }
        }
        let IsSupportCODIndex = values.Payment.findIndex(item => item == 2)
        if (IsSupportCODIndex > -1) {
          values = { ...values, IsSupportCOD: true }
        } else {
          values = { ...values, IsSupportCOD: false }
        }
        dispatch({
          type: `${namespace}/SaveExpressConfig`,
          param: values,
          callback: {
            success: (data) => {
              message.success("设置成功");
            },
            error: (data) => {
              message.error("设置失败：" + data.Msg);
            }
          }

        });
      }
    });
  }
  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 2 },
        sm: { span: 2 },
        md: { span: 2 },

      },
      wrapperCol: {
        xs: { span: 22 },
        sm: { span: 22 },
        md: { span: 22 },
      },
    };
    const {
      getFieldDecorator, getFieldsError, getFieldError, isFieldTouched, getFieldValue
    } = this.props.form;
    const { Payment, paginationProps } = this.state;
    const { expresssetting: { expressConfig, pageFreightTemplate }, loadBtn, loading, loadList } = this.props;

    const listData = [{ name: '213123' }, { name: '213123' }, { name: '213123' }, { name: '213123' }];
    return (
      <Fragment>
        {/* <HeaderTab
          _this={this}
          type="slider"
          activeId={this.state.activeId}
          onChange={this.onTabChange}
          tabs={this.state.tabs}
        >
        </HeaderTab> */}
        <Spin spinning={loading || loadList} >
          <Card
            title="快递发货功能"
            bordered={false}
            className={styles.ExpressTitle}
          >
            <div>
              买家下单可以选择快递发货，由你安排快递送货上门。<a>查看【运费模板】使用教程</a>
            </div>
            <Switch
              onChange={this.setExpressConfig}
              checked={expressConfig && expressConfig.Status && expressConfig.Status == 1 ? true : false}
              defaultChecked={expressConfig && expressConfig.Status && expressConfig.Status == 1 ? true : false}
            />
          </Card>
          <Card
            title="快递发货设置"
            bordered={false}
            className={styles.ExpressSet}
          >
            <Form >
              <FormItem
                {...formItemLayout}
                label="计费方式"
              >

                {getFieldDecorator('BillingMode', {
                  initialValue: expressConfig && expressConfig.BillingMode ? expressConfig.BillingMode : 2,
                  rules: [{ required: true, message: '请选择计费方式' }],
                })(
                  <RadioGroup  >
                    <Radio value={1}>按商品累计运费</Radio>
                    <Radio value={2}>组合运费（推荐使用）</Radio>
                  </RadioGroup>
                )}
                <a>运费计算规则</a>
              </FormItem>

              <FormItem
                {...formItemLayout}
                label="支付方式"
              >
                {getFieldDecorator('Payment', {
                  initialValue: Payment,
                  rules: [{ required: true, message: '请选择至少一种支付方式!' }],
                })(
                  <Checkbox.Group >
                    <Checkbox value={1}>在线支付</Checkbox>
                    <Checkbox value={2}>货到付款</Checkbox>
                  </Checkbox.Group>
                )}

              </FormItem>

              <Row>
                <Col offset={2}>
                  <Button
                    type="primary"
                    // htmlType="submit"
                    loading={loadBtn}
                    onClick={this.handleSubmit}
                  >
                    保存
                </Button>
                </Col>
              </Row>
            </Form>
          </Card>
          <Card
            title="运费模板设置"
            className={styles.MubanSet}
          >
            <Button
              type="primary"
              onClick={this.AddTemplate}

            >
              新建运费模板
          </Button>
            <List
              itemLayout="vertical"
              size="large"
              dataSource={pageFreightTemplate && pageFreightTemplate.DataList ? pageFreightTemplate.DataList : []}
              renderItem={item => (
                <List.Item>
                  <Row>
                    <Col span={9}>模板名称：{item.Name}</Col>
                    <Col span={8}>使用该模板的商品：{item.ProductNum}个</Col>
                    <Col span={7}>最后编辑时间：{item.ModifiedTime}</Col>
                  </Row>
                  <Row>
                    <Col span={9}>配送区域</Col>
                    <Col span={2}>首件(件)</Col>
                    <Col span={2}>运费(元)</Col>
                    <Col span={2}>续件(件)</Col>
                    <Col span={2}>续费(元)</Col>
                    <Col span={4}>操作</Col>
                  </Row>
                  {
                    item.ValuationRules && item.ValuationRules.map((rule, index) => {

                      return <Row key={index}>
                        <Col span={9}>{!rule.IsDefault ? rule.RegionNames.join(',') : '默认运费'}</Col>
                        <Col span={2}>{rule.FirstAmount}</Col>
                        <Col span={2}>{rule.FirstFee}</Col>
                        <Col span={2}>{rule.AdditionalAmount}</Col>
                        <Col span={2}>{rule.AdditionalFee}</Col>
                        {
                          index == 0 ? <Col span={4}>
                            <div className="Act" >
                              <a onClick={() => this.editTemplate(item.Id)}>编辑</a>|
                              {/* <a>复制</a> */}
                              <Popconfirm title="确认删除？" onConfirm={() => this.deleteTemp(item.Id)} okText="确认" cancelText="我再想想">
                                <a>删除</a>
                              </Popconfirm>
                              {/* |<a>查看商品</a> */}
                            </div>
                          </Col> : null
                        }
                      </Row>
                    })
                  }

                </List.Item>
              )}
            />

            <Pagination
              showSizeChanger
              onChange={this.onShowSizeChange}
              showTotal={paginationProps.showTotal}
              total={paginationProps.total}
              current={paginationProps.pageIndex}
              pageSize={paginationProps.pageSize}
            />
          </Card>
        </Spin>
      </Fragment>
    )
  }
}
export default connect(({ expresssetting, global, loading }) => ({
  expresssetting,
  loading: loading.effects['expresssetting/GetExpressConfig'],
  loadBtn: loading.effects['expresssetting/SaveExpressConfig'],
  loadList: loading.effects['expresssetting/GetFreightTemplateWithPage'],
}))(Express);